import Vue from 'vue'
import Vuex from 'vuex'
import server from '@/utils/server'
import ServerConstants from '@/utils/ServerConstants'

Vue.use(Vuex)

const store = new Vuex.Store({

  state: {
    hasLogin: false,
    userInfo: server.getUserInfo(),
    cartInfo: server.getCartInfo(),

  },
  getters: {
    cartInfo: state => state.cartInfo,
    userInfo: state => state.userInfo,
    hasLogin: state => state.hasLogin,
  },
  mutations: {
    getCartInfo (state) {
      return state.cartInfo
    },
    login (state, provider) {
      server.saveUserInfo(provider)
      state.hasLogin = true
      state.userInfo = provider
      server.saveCartInfo(server.getCartInfo())
      state.cartInfo = server._isEmpty(server.getCartInfo())
        ? {}
        : server.getCartInfo()
      //登录的时候，把购物车数据保存到服务器
      server.updateRefresh(ServerConstants.HAS_LOGIN,1)
    },
    logout (state) {
      server.delUserInfo()
      state.hasLogin = false
      state.userInfo = {}
      state.cartInfo = {}
      server.updateRefresh(ServerConstants.HAS_LOGIN,1)
    },
    addCart (state, provider) {
      if (server._isEmpty(provider) || provider.length <= 0) {
        server.msg('添加商品不能为空')
        return
      }
      server.addCartInfo(provider)
      server.successMsg('加入购物车成功')
    },
    saveCart (state, provider) {
      server.saveCartInfo(provider)
    },
    setCartInfo (state, provider) {
      state.cartInfo = provider
      console.log(state.cartInfo)
    },
    setUserInfo (state, provider) {
      if (server._isEmpty(provider)) {
        state.userInfo = {}
        return
      }
      state.userInfo = provider
    },
    setHaslogin (state, provider) {
      state.hasLogin = provider
    },
  },
  actions: {
    saveCart ({commit}, arg) {
      commit('saveCart', arg)
    },
    addCart ({commit}, arg) {
      commit('addCart', arg)
    },

  },
})

export default store
